package com.sci99.ex.util;

import java.io.IOException;
import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

public class MyBatisUtil {
	static Logger log = Logger.getLogger(MyBatisUtil.class);
	/**
	 * iBatis配置文件
	 */
	static final String IBSConfig = "mybatis.xml";
	/**
	 * MySQL
	 */
	static SqlSessionFactory mysqlFactory;
	/**
	 * MS SQLServer
	 */
	static SqlSessionFactory mssqlFactory;
	/**
	 * H2db
	 */
	static SqlSessionFactory h2Factory;

	/**
	 * 获取默认数据库 Session
	 * 
	 * @return SqlSession
	 * @throws IOException
	 */
	public static SqlSession getSession() throws IOException {
		// return getSessionFactory().openSession();
		return getMySqlSession();
	}

	public static SqlSession getH2Session() throws IOException {
		if (h2Factory == null) {
			InputStream inputStream = Resources.getResourceAsStream(IBSConfig);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			h2Factory = builder.build(inputStream, "h2");
		}
		return h2Factory.openSession();
	}

	/**
	 * 获取 SQLServer Session
	 * 
	 * @return SqlSession
	 * @throws IOException
	 */
	public static SqlSession getMsSqlSession() throws IOException {
		if (mssqlFactory == null) {
			InputStream inputStream = Resources.getResourceAsStream(IBSConfig);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			mssqlFactory = builder.build(inputStream, "sqlserver");
		}
		return mssqlFactory.openSession();
	}

	/**
	 * 获取 MySQL Session
	 * 
	 * @return SqlSession
	 * @throws IOException
	 */
	public static SqlSession getMySqlSession() throws IOException {
		if (mysqlFactory == null) {
			InputStream inputStream = Resources.getResourceAsStream(IBSConfig);
			SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
			mysqlFactory = builder.build(inputStream, "mysql");
		}
		return mysqlFactory.openSession();
	}
}
